<?php
/**
 * Created by PhpStorm.
 * User: Admin
 * Date: 2020-08-08
 * Time: 下午 04:08
 */
namespace Cmd;
use Cmd\Base\User;
use Lib\Cmd;

class Passwd extends User {
    protected $_options = ['hash', ':db'];
    
    public function main() {
        $username = $this->getArgv(0);
        $hashMethod = strtolower($this->getParam('hash', 'pwdhash'));

        if(empty($username)) {
            return $this->help();
        }
        
        if(!in_array($hashMethod, $this->userModel->getAvailableHashMethods())) {
            $this->writeError("不支持的hash: '$hashMethod'");
        }

        if(!$this->userModel->exists($username)) {
            $this->writeError('用户不存在');
        }
        
        $password = $this->inputSecurely('　输入新密码:', '●');
        $repassword = $this->inputSecurely('再次输入密码:', '●');

        if($password != $repassword) {
            $this->writeError('两次输入的密码不一致');
        }

        if($this->userModel->updatePassword($username, $password)) {
            $this->writeSuccess("密码修改成功");
        }

        $this->writeError("密码修改失败");
    }

    public function help() {
        $this->writeInfo("功能: 修改用户密码");
        $this->writeInfo("用法: ./exec passwd (username) [--option[=value]]");
        $this->writeLn();
        $this->writeInfo("args:");
        $this->writeLn();
        $this->writeInfo("  username: 用户名");
        $this->writeLn();
        $this->writeInfo("options:");
        $this->writeLn();
        $this->writeInfo("  --hash 哈希算法, 可选值有".
            implode(',', $this->userModel->getAvailableHashMethods())
            ."  默认为 pwdhash");

        $this->writeLn();
    }
}